package org.andcool.application;

import org.andcool.sensor.location.ILocationListener;
import org.andcool.sensor.location.LocationProviderStatus;
import org.andcool.sensor.location.LocationSensorOptions;

import android.app.Application;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;

/**
 * @author Joosun
 * @since 2011-7-13
 */
public class AndCoolApplication extends Application implements LocationListener
{
	private Location mLocation;
	private ILocationListener mLocationListener;

	public void enableLocationSensor(final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions)
	{
		this.mLocationListener = pLocationListener;

		final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

		final String locationProvider = locationManager.getBestProvider(pLocationSensorOptions, pLocationSensorOptions.isEnabledOnly());

		locationManager.requestLocationUpdates(locationProvider, pLocationSensorOptions.getMinimumTriggerTime(), pLocationSensorOptions.getMinimumTriggerDistance(), this);

		this.onLocationChanged(locationManager.getLastKnownLocation(locationProvider));
	}

	public void disableLocationSensor()
	{
		final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationManager.removeUpdates(this);
	}

	@Override
	public void onLocationChanged(final Location pLocation)
	{
		if (this.mLocation == null)
		{
			this.mLocation = pLocation;
		}
		else
		{
			if (pLocation == null)
			{
				this.mLocationListener.doLocationLost();
			}
			else
			{
				this.mLocation = pLocation;
				this.mLocationListener.doLocationChanged(pLocation);
			}
		}
	}

	@Override
	public void onProviderDisabled(final String pProvider)
	{
		this.mLocationListener.doLocationProviderDisabled();
	}

	@Override
	public void onProviderEnabled(final String pProvider)
	{
		this.mLocationListener.doLocationProviderEnabled();
	}

	@Override
	public void onStatusChanged(final String pProvider, final int pStatus, final Bundle pExtras)
	{
		switch (pStatus)
		{
			case LocationProvider.AVAILABLE:
				this.mLocationListener.doLocationProviderStatusChanged(LocationProviderStatus.AVAILABLE, pExtras);
				break;
			case LocationProvider.OUT_OF_SERVICE:
				this.mLocationListener.doLocationProviderStatusChanged(LocationProviderStatus.OUT_OF_SERVICE, pExtras);
				break;
			case LocationProvider.TEMPORARILY_UNAVAILABLE:
				this.mLocationListener.doLocationProviderStatusChanged(LocationProviderStatus.TEMPORARILY_UNAVAILABLE, pExtras);
				break;
			default:
				break;
		}
	}
}